require 'yaml'

module Termarks

  #
  # Bookmarks Manager class
  # Main class for manipulate the bookmarks file.
  #
  class BookmarkManager

    # bookmarks store
    @@bookmarks = {}

    #
    # get the location yaml file that stores the bookmarks
    #
    def self.bookmarks_file
        File.join(Dir.home, ".termarks.yml")
    end

    #
    # loads the bookmarks into memory
    #
    def self.load
        unless File.exists?(bookmarks_file)
            f = File.open(bookmarks_file, 'w')
            f.sync = true # forces file to be immediately written, Otherwise the @@bookmarks would be empty on the first run.
            f.puts(File.read(File.expand_path("../../../templates/termarks.yml", __FILE__)))
        end

        @@bookmarks = YAML.load_file(bookmarks_file)
    end

    #
    # saves a new bookmark
    # @param [String] The bookmark identifier.
    # @param [String] The command to bookmark
    # @param [String] The description of the command
    #
    def self.add(identifier, cmd, description = nil, tags = nil)

      @@bookmarks['termarks'][identifier] = {
        'cmd'         => cmd,
        'description' => description.nil? ? " " : description,
      }

      self.save_to_file

    end

    #
    # Returns all bookmarks
    # @return [Hash] The list of bookmarks
    #
    def self.get_bookmarks
        @@bookmarks['termarks']
    end

    #
    # Removes an existing bookmark
    # @param [String] The bookmark identifier
    #
    def self.delete identifier
      if not @@bookmarks['termarks'].has_key? identifier
        raise "No bookamrk found for '#{identifier}'"
      end

      @@bookmarks['termarks'].delete(identifier)
      self.save_to_file
    end

    #
    # writes the bookmarks to yaml file
    #
    def self.save_to_file
      File.open(bookmarks_file, 'w') {|f| f.write @@bookmarks.to_yaml }
    end

    #
    # Validates bookmark identifier
    # @param [String] The bookmark identifier.
    #
    def self.validate_identifier(identifier)

      # check if identifier is valid.
      unless identifier =~/^[a-zA-Z0-9_]+$/
        raise "Invalid Identifier '#{identifier}'. It should contain only letters, numbers and underscores."
      end

      # checks if a bookmark with that identifier already exists.
      unless @@bookmarks['termarks'].has_key?(identifier)
        raise "A bookmark with the '#{identifier}' identifier already exists."
      end

    end
  end
end
